<template>
  <div class="base-page"  :style="{ height:screenHeight-20+'px'}">
    <div style="height:100%" class="right select-item" v-show="viewList === true">
      <div class="e-table">
        <div class="top">
          <div class="left">
            <div class="left-btn">
              <el-button type="primary" size="mini"
                         @click="goAdd"
                         class="btn-greenYellow"
              >添加新项</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="e-table">
        <div class="e-tree-table"  :style="{ height:screenHeight-50+'px'}">
          <el-table
              :data="tableData"
              style="width: 100%; margin-bottom: 20px"
              row-key="billId"
              border
              ref="tableRef"
              :tree-props="{
                          children: 'children',
                          hasChildren: 'hasChildren',
                      }"
              :cell-class-name="cellClsNm"
              @cell-mouse-enter="cellMouseEnter"
              @cell-mouse-leave="cellMouseLeave"
              @expand-change="switchRow"
              class="table"
              v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
          >
            <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
            <el-table-column label="操作" fixed width="250px" align="left"  sortable>
              <template slot-scope="{ row }">
                <div class="oparation_box">
                  <img src="@/assets/btn/sub.png" class="add_sub"
                    @click="addChild(row)"
                    title="添加子级"
                    />
                  <i
                      class="el-icon-edit"
                      style="font-size: 24px"
                      :class="{
                                          'icon-edit-active-color': MouseEnterId == row.billId
                                      }"
                      title="编辑"
                      @click="edit(row)"
                  ></i>
                  <!-- <i
                      class="el-icon-delete"
                      style="font-size: 24px"
                      :class="{
                                          'icon-delete-active-color': MouseEnterId == row.billId
                                      }"
                      title="删除"
                      @click="deleteEle(row)"
                  ></i> -->
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="kvDescription" fixed label="编号"> </el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="state" label="状态">
              <template slot-scope="{ row }">
                {{shuziShow(row.state)}}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 新增编辑界面 -->
    <div class="right" v-if="viewList === 'add' || viewList === 'edit'">
      <div class="e-form" style="padding: 0 10px 10px;">
        <div class="tabs-title">合同类别维护</div>
        <el-form ref="form" :model="formData" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称：" prop="name">
                <el-input v-model="formData.name" placeholder="请输入名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span='12'>
              <el-form-item label="启用状态" prop="state">
                <el-select v-model="formData.state" placeholder="请选择启用状态">
                  <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="footer">
        <div class="right-btn">
          <el-button type="primary" size="mini"
                     @click="onSave"
          >保存</el-button>
          <el-button type="default" size="mini"
                     @click="onCancel"
          >取消</el-button>
        </div>
      </div>
    </div>
    <!-- 新增子级的界面 -->
    <div class="right" v-else-if="viewList === 'addChild' || viewList === 'editChild'">
      <div class="e-form" style="padding: 0 10px 10px;">
        <div class="tabs-title">合同类别维护</div>
        <el-form ref="formRef" :model="getListData" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="父节点编号：">
                <span>{{ parent.number }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="父节点名称：">
                <span>{{ parent.name }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="子节点名称：" prop="kvDescription">
                <el-input v-model="getListData.name" placeholder="请输入名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="子节点状态：" prop="state">
                <el-select v-model="getListData.state" placeholder="请选择启用状态">
                  <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="footer">
        <div class="right-btn">
          <el-button type="primary" size="mini"
                     @click="onSaveChild"
          >保存</el-button>
          <el-button type="default" size="mini"
                     @click="onCancel"
          >取消</el-button>
        </div>
      </div>
      <ComPagination
          :total="totalPage"
          :pageSize.sync="pagination.limit"
          :currentPage.sync="pagination.page"
          @currentChange="contractListByEntity"
          @sizeChange="contractListByEntity"
          class="bottomSetting"
      />
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import ComPagination from '@/components/pagination/pagination'
import { debounce, getUuid } from '@/utils/common'
import { setContractList, getContractList } from '@/api/base/contract'
export default {
    data () {
        return {
            options: [{
                value: 0,
                label: '禁用'
            }, {
                value: 1,
                label: '启用'
            }, ],
            value: '',
            hasChildren: true,
            formData: {
                'billId': getUuid(),
                'name': '',
                'parentId': '',
                'state': 0
            },
            getListData: {
                'billId': getUuid(),
                'name': '',
                'parentId': '',
                'state': 0
            },
            parent: {
                'billId': getUuid(),
                'name': '',
                'parentId': '',
                'state': 0
            },
            upData: {
                'billId': '',
                'name': '',
                'state': 0
            },
            childrenData: {
                'billId': '',
                'children': [
                    {
                        'billId': '',
                        'children': [
                            {}
                        ],
                        'name': '',
                        'number': '',
                        'parentId': '',
                        'state': '',
                        'subscript': 0,
                    }
                ],
                'name': '',
                'number': '',
                'parentId': '',
                'state': 0,
                'subscript': 0,
            },
            //以下为待修改数据****************************
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            pagination: {   //没有参数数据
                'total': 0,
                'limit': 10,
                'page': 1,
            },
            tableData: [],
            rules: {
                state: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                ],
            },
            params: {
                'key': '',
                'parentId': '',
                'isEnable': false,
            },
            selectData: null,
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            tableView: false, //控制表格是否重新渲染
            mapData: {}, //存储当前节点信息
            MouseEnterId: 0,
            isDelete: false
        }
    },
    components: {
        ComPagination
    },
    computed: {
    // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 280) + 'px'
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        }
    },
    mounted () {
        this.getTableData()
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
    //状态数字转换
        shuziShow (state) {
            if(state == 0) {
                return '禁用'
            }else if(state == 1) {
                return '启用'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //获取列表数据
        getTableData () {
            this.params.parentId = '0'
            this.tableData = []
            getContractList(this.params).then(res=>{
                const fn = data =>{
                    data.forEach(item=>{
                        item.isExpand = false
                    })
                    this.tableData = data
                    this.tableView = true
                }
                fn(res)
            })
        },
        loadTableTree (tree, treeNode, resolve) {
            if(treeNode.children.length > 0) {
                setTimeout(()=>{
                    this.$refs.tableRef.toggleRowExpansion(tree, false)
                }, 10)
            }
            this.parent.parentId = tree.billId
            this.mapData[tree.billId] = { tree, treeNode, resolve }
            setContractList(this.parent).then(res=>{
                const fn = data => {
                    data = data ? data : []
                    data.forEach(item=>{
                        item.hasChildren = !item.isLeaf
                        item.isExpand = false
                    })
                    tree.children = data
                    resolve(data)
                }
                fn(res)
            })
        },
        switchStatus () {
            const fn1 = value=>{
                value.forEach(item=>{
                    setTimeout(()=>{
                        this.$refs.tableRef.toggleRowExpansion(item, item.isExpand)
                    }, 10)
                    if(item.hasChildren && item.children && item.isExpand) {
                        fn1(item.children)
                    }
                })
            }
            fn1(this.tableData)
        },
        onSelectOrg (val) {
            this.formData = {
                ...val,
                currency: 10
            }
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            this.params.dicKey = searchKey
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            this.getTableData()
        },
        goAdd () {
            // 添加顶级时，设置选中项为空
            this.selectData = null
            this.viewList = 'add'
            this.formData
        },
        //添加子级
        addChild (row) {
            console.log(row)
            this.parent = row
            this.getListData
            this.getListData.parentId = row.billId
            if(row.isLeaf === 1 || !row.children || row.children.length === 0) {
                this.childrenData.number = row.number + '-1'
            }else{
                const arr = row.children[row.children.length - 1].number.split('-')
                arr.splice(-1, 1, Number(arr[arr.length - 1]) + 1)
                this.childrenData.number = arr.join('-')
            }
            this.viewList = 'addChild'
        },
        edit (row) {
            console.log(row)
            if(row.parentId === '0') {
                this.formData = this._.clone(row)
                this.viewList = 'edit'
            }else{
                this.childrenData = this._.clone(row)
                console.log('upData', this.childrenData )
                const fn = data => {
                    for(let i = 0; i < data.length; i++) {
                        if(data[i].children) {
                            if(data[i].billId === row.parentId) {
                                this.getListData = row
                                this.parent = data[i]
                                this.viewList = 'editChild'
                                return
                            }else{
                                fn(data[i].children)
                            }
                        }
                    }
                }
                fn(this.tableData)
            }
        },
        onSave () {
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    setContractList(this.formData).then(res => {
                        console.log(res)
                        this.clientPop('suc', '保存成功', () => {
                            this.updateEle(this.formData.parentId)
                            this.viewList = true
                        })
                    })
                }
            })
        },
        // ***********************接口未出
        //删除节点
        // deleteEle (row) {
        deleteEle () {
            // 删除接口当时还没出来
            // 先提示，再删除
            // this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作', () => {
            //     deleteCurrencyTree(row).then(() => {
            //         this.clientPop('suc', '删除成功', () => {
            //             const id = row.parentId
            //             console.log('id: ', id)
            //             if(this.mapData[id]) {
            //                 const { tree, treeNode, resolve } = this.mapData[id]
            //                 this.$set(this.$refs.tableRef.store.states.lazyTreeNodeMap, id, [])
            //                 // 如果还有兄弟，则重新加载父节点，否则重新加载父节点的父节点，刷新目录状态
            //                 // 删除后还有，所以 > 1
            //                 if (tree.children.length > 1) {
            //                     this.loadTableTree(tree, treeNode, resolve)
            //                 } else {
            //                     if (tree.parentId === '0') {
            //                         this.getTableData()
            //                     } else {
            //                         this.loadTableTree(this.mapData[tree.parentId].tree, this.mapData[tree.parentId].treeNode, this.mapData[tree.parentId].resolve)
            //                     }
            //                 }
            //             } else {
            //                 this.getTableData()
            //             }
            //         })
            //     })
            // })
        },
        //操作节点后更新父节点
        updateEle (billId) {
            console.log(billId)
            if(billId === '') {
                this.tableView = false
                this.getTableData()
                return
            }else{
                let params = { ...this.params }
                params.parentId = billId
                console.log(this.params.parentId)
                getContractList(this.params).then(res=>{
                    console.log(res)
                    const fn = data =>{
                        data = data ? data : []
                        data.forEach(item=>{
                            item.hasChildren = !item.isLeaf
                        })
                        const fn1 = item=>{
                            for(let i = 0;i < item.length;i++) {
                                if(item[i].billId === billId) {
                                    this.parent = item[i]
                                    // item[i].isLeaf = 0
                                    item[i].children = data
                                    item.isExpand = false
                                    if(item[i].parentId === '0') {
                                        item[i].hasChildren = !this.isDelete
                                    }
                                    this.isDelete = false
                                    return
                                }else{
                                    if(item[i].children) {
                                        fn1(item[i].children)
                                    }
                                }
                            }
                        }
                        fn1(this.tableData)
                        this.switchStatus()
                    }
                    fn(res)
                })
            }

        },
        switchRow (row, expanded) {
            row.isExpand = expanded
        },
        //保存子级
        onSaveChild () {
            this.$refs['formRef'].validate(async valid => {
                if (valid) {
                    setContractList(this.getListData).then(() => {
                        this.clientPop('suc', '保存成功', () => {
                            this.updateEle(this.parent.parentId)
                            this.viewList = true
                            // this.tableView = false
                        })
                    })
                }
            })
        },
        //取消
        onCancel () {
            this.viewList = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
    }
}
</script>

<style lang="scss" scoped>
.select-item {
  width: 60%;
  height: 90%;

  margin: auto;

  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .top {
    height: 50px;
    display: flex;
    justify-content: space-between;
    .info {
      width: 60px;
      height: 50px;
      line-height: 50px;
      position: relative;
      .tabs-title::before {
        content: "";
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 0px;
        top: 14px;
      }
    }
    .ipt-box {
      width: 210px;
      height: 50px;
      position: relative;
      .ipt{
        border: 0;
        width: 200px;
        height: 30px;
        border-radius: 5px;
        margin-top: 12px;
        box-sizing: border-box;
        padding-left: 20px;
        border: 1px solid #ccc;
      }
      img{
        height: 15px;
        width: 15px;
        position: absolute;
        top: 20px;
        right: 19px;
        cursor: pointer;
      }
      ::placeholder{
        padding-left: 15px;
        font-weight: 700;
      }
    }
  }
  .table {
    flex: 1;
    border-radius: 5px;
    margin-top: 10px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    ::v-deep.has-gutter th {
      background: #e0e7f9 !important;
      color: #000;
    }
    ::v-deep.el-table--enable-row-hover .el-table__body tr:hover {
      font-weight: bold;
    }
    ::v-deep.el-table ::v-deep .el-table__expand-icon--expanded {
      transform: none;
    }
    ::v-deep.el-tree ::v-deep .el-tree-node__expand-icon.expanded {
      -webkit-transform: rotate(0deg);
      transform: rotate(0deg);
    }
  }
  .footer {
    height: 50px;
    display: flex;
    background-color: #eff2f6;
    .left {
      width: 60%;
      height: 50px;
    }
    .right {
      line-height: 50px;
      font-weight: 500;
      color: rgb(233, 84, 66);
      font-size: 14px;
      .colse-btn {
        background-color: #fff;
        color: #000;
      }
    }
    ::v-deep.el-button--mini {
      width: 60px;
      color: #fff;
      margin-left: 10px;
      background-color: rgb(46, 97, 215);
    }
  }
}
.e-tree-table{
  border: none;
}
.right{
  border: none;
}
::v-deep .el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(1){
            .cell{
                justify-content: flex-start;
            }
        }
    }
    ::v-deep .has-gutter{
        .cell{
            display: flex;
            align-items: center;
        }
        th:nth-child(1){
            .cell{
                text-align: left;
            }
        }
    }
</style>
